package com.xiachufang.app.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiachufang.app.common.Res;
import com.xiachufang.app.entity.User;
import com.xiachufang.app.service.UserService;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.annotation.Resource;

@Api("User相关接口")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;


    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Res<?> login(@RequestBody User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        String securePass = SecureUtil.md5(user.getPassword() + user.getUsername());
        queryWrapper.eq("password", securePass);
        User res = userService.getOne(queryWrapper);
        if (res == null) {
            return Res.error("用户名或密码错误");
        }
        return Res.success(res);
    }


    /**
     * 先更新 再新增
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "新增或更新User对象")
    @PostMapping
    public Res<?> save(@RequestBody User user) {
        boolean update = userService.updateById(user);
        if (!update) {
            userService.save(user);
        }
        return Res.success();
    }

    @ApiOperation(value = "根据id删除User对象")
    @DeleteMapping("/{id}")
    public Res<?> delete(@PathVariable Integer id) {
        userService.removeById(id);
        return Res.success();
    }

    @ApiOperation(value = "查询所有User对象")
    @GetMapping
    public Res<?> all() {
        return Res.success(userService.list());
    }

    @ApiOperation(value = "根据id查询User对象")
    @GetMapping("/{id}")
    public Res<?> getById(@PathVariable Integer id) {
        return Res.success(userService.getById(id));
    }


    /**
     * 分页查询接口
     *
     * @param pageNum  页码
     * @param pageSize 每页个数
     * @param name     模糊查询关键字
     * @return page对象
     */
    @ApiOperation(value = "分页查询接口")
    @GetMapping("/page")
    public Res<?> page(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                       @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                       @RequestParam(required = false, defaultValue = "") String name) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        return Res.success(userService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }
}

